package com.huo.common.quartz.factory;


import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.huo.task.dao.ScheduleJob;
import com.huo.util.SpringContextUtil;


/**
 * QuartzJob工厂类
 * DisallowConcurrentExecution 不允许并发执行（预设的任务执行时间间隔失效）
 * 程序会等任务执行完毕以后再去执行,否则会在3秒（预设的任务执行时间 --时间表达式）时再启用新的线程执行 
 * 
 */
@DisallowConcurrentExecution
public class QuartzJobFactory implements Job {
	private static final Logger log = LoggerFactory.getLogger(QuartzJobFactory.class);
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
    	ScheduleJob scheduleJob =  (ScheduleJob) context.getMergedJobDataMap().get("scheduleJob");
        try {
        	String beanName  = classNameToBeanName(scheduleJob.getBeanClass());
        	log.debug("【INVOKE JobClassName:"+scheduleJob.getBeanClass()+"-------------"+"\nbeanName:"+beanName+"\nfuncationName:"+scheduleJob.getMethodName()+"】");
        	Class<?> c = Class.forName(scheduleJob.getBeanClass());
			c.getMethod(scheduleJob.getMethodName()).invoke(SpringContextUtil.getBean(beanName));
		} catch (Exception e) {
			e.printStackTrace();
		} 
    	
    }
    
    /**
	 * 截取className最后一段，并大写首字母 得到beanName
	 * @param length className
	 * @return beanName
	 */
	public static String classNameToBeanName(String className) {
		StringBuffer sb =new  StringBuffer(className);
		StringBuffer tempsb =new  StringBuffer(sb.substring(sb.lastIndexOf(".")+1, sb.length()));
		String beanName =tempsb.toString().replaceFirst(tempsb.substring(0, 1),tempsb.substring(0, 1).toLowerCase());
		return beanName ;
		
	}
    
}
